﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using System.IO;

namespace DSServer.Banking
{
    class BankI : BankDisp_
    {
        private static readonly ILog log = log4net.LogManager.GetLogger(typeof(BankI));

        private readonly int[] peselWeights = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1};
        private readonly int peselLength = 11;
        private readonly object locker = new object();
        private readonly string directory = "BankAccounts";

        private bool isValidPesel(string PESEL){
            int sum=0;
            if (PESEL.Length != peselLength)
                return false;
            
            for (int i = 0; i < peselLength; ++i)
            {
                if(! char.IsDigit(PESEL[i]))
                    return false;
                sum += ((int)PESEL[i] - (int)'0')*peselWeights[i];
            }
            
            return sum % 10==0;
        }

        internal void login(string PESEL, string password)
        {
            if (!isValidPesel(PESEL))
                throw new PeselInvalidException(PESEL);
            lock (locker)
            {
                CheckAccount(PESEL,password);
            }
        }


        private void CheckAccount(string PESEL, string password)
        {
            string file = directory + "/" + PESEL;
            if (!File.Exists(file))
            {
                throw new InvalidPeselOrPasswordException();
            }
            try
            {
                if (File.ReadAllLines(file)[0] != password)
                    throw new InvalidPeselOrPasswordException();
            }
            catch (InvalidPeselOrPasswordException)
            {
                throw;
            }
            catch (Exception e)
            {
                log.Error(e);
                throw;
            }
        }


        public override void createAccount(string PESEL, string password, Ice.Current current__)
        {
            if (!isValidPesel(PESEL))
                throw new PeselInvalidException(PESEL);
            lock (locker)
            {
                string file = directory + "/" + PESEL;
                if(File.Exists(file))
                    throw new PeselAlreadyUsedException();
                File.WriteAllLines(file,new string[] {password, "0.0"});
            }
        }

        public override void destroyAccount(string PESEL, string password, Ice.Current current__)
        {
            if (!isValidPesel(PESEL))
                throw new PeselInvalidException(PESEL);
            lock (locker)
            {
                CheckAccount(PESEL,password);               
                File.Delete(directory + "/" + PESEL);           
            }
        }
    }
}
